package org.jb.coinche.server.rooms;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class RoomFilter implements Filter {

	/*
	 * 
	 */
	@Inject
	public RoomFilter( RoomScope scope ) {
		this.scope = scope;
	}
	
	/*
	 * (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		String room = null;
		
		if (request instanceof HttpServletRequest) {
			HttpServletRequest req = (HttpServletRequest)request;
			
			String query = req.getQueryString();
			if (query != null && query.startsWith("room=")) {
				room = query.substring(5);
			}
		}
		
		try {
			scope.setRoom( room );
			
			chain.doFilter(request, response);	
		}
		finally {
			scope.setRoom( null );
		}
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	
	}

	private RoomScope scope;
}
